#!/usr/bin/env bash
#
# Copyright (C) Hygon Info Technologies Ltd.
#
# SPDX-License-Identifier: Apache-2.0
#

set -o errexit
set -o errtrace
set -o pipefail

readonly script_name="$(basename "${BASH_SOURCE[0]}")"
readonly script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly sftp_tool="$script_dir/../../../tools/sftp"
readonly pkg_dir="${script_dir}/../pkg"
readonly dcu_driver_tar_name="rock-kernel-5.11.36.tar.gz"
mkdir -p "${pkg_dir}"

# now the supported kernel version is 5.11.0
readonly kernel_ver="5.11.0"

lib_file="${script_dir}/lib.sh"
source "$lib_file"

typeset rootfs_dir=

#$1: Error code if want to exit different to 0
usage() {
	error="${1:-0}"
	cat <<EOF

Usage: ${script_name}  [rootfs_dir]

install dcu kernel driver into rootfs directory, used to create
Kata Containers images or initramfs.

EOF
exit "${error}"
}

parse_arguments() {
	[ "$#" -eq 0 ] && usage && return 0

	rootfs_dir="$1"
	if [ ! -d "${rootfs_dir}" ]; then
		die "${rootfs_dir} is not an existing directory"
	fi
}

install_dcu_driver() {
	pushd "${pkg_dir}"
	if [ ! -f "${dcu_driver_tar_name}" ]; then
		if [ ! -f $sftp_tool]; then
			wget https://gitee.com/anolis/hygon-devkit/raw/master/tools/sftp
    		chmod +x sftp
			./sftp download /hygon-devkit/4.0/2025-01-01/csv/confidential-containers/pkg/${dcu_driver_tar_name} ./${dcu_driver_tar_name}
		else
			$sftp_tool download /hygon-devkit/4.0/2025-01-01/csv/confidential-containers/pkg/${dcu_driver_tar_name} ./${dcu_driver_tar_name}
		fi
	fi
	tar xvf "${dcu_driver_tar_name}" -C "${rootfs_dir}"
	echo "options hydcu hygon_vbios=0" > "${rootfs_dir}"/etc/modprobe.d/hydcu.conf
	depmod -b "${rootfs_dir}" ${kernel_ver}
}

main() {
	check_root
	parse_arguments $*

	install_dcu_driver

	OK "DCU kernel driver is installed, enjoy!"
}

main $*
